<!--
 * @Author: your name
 * @Date: 2022-04-14 10:16:32
 * @LastEditTime: 2022-04-14 11:24:28
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \postapiGen\index.html
-->
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>PostApi 接口提取</title>
		<div>只提取了根目录下的子目录接口，根目录下的接口不提取</div>
		<script src="data.js"></script>
	</head>
	<body>
		<script>
			let rawList = data.data.list;
			console.log('raw', rawList);
			let mainFolders = rawList.filter((m) => m.target_type === 'folder' && m.parent_id === '0');
			// console.log('mainFolders', mainFolders);

			let mainApis = rawList.filter((m) => m.target_type === 'api' && m.parent_id === '0');
			console.log('mainApis', mainApis);

			mainFolders.forEach((element) => {
				let subFolders = rawList.filter((m) => m.parent_id == element.target_id);
				// console.log('subFolders ' + element.name, subFolders);
				var codeList = [];

				subFolders.forEach((inner) => {
					let subApis = rawList.filter((m) => m.parent_id == inner.target_id);
					// console.log('subApis ' + inner.name, subApis);

					var res = generateApis(inner.name, subApis);
					codeList.push(res);
				});

				var codeRes = generateObj(element.name, element.name, codeList.join(''));
				console.log(codeRes);
			});

			function generateObj(key, desc, value) {
				return `
          /**
            * ${desc}
          */
          const ${key} = {
              ${value} 
            };
        `;
			}
			function generateObjItem(key, desc, value) {
				return `
          /**
            * ${desc}
          */
          ${key}Api : {
              ${value} 
            },
        `;
			}
			function generateApis(name, list) {
				if (!list || list.length === 0) return;

				let [, key, fun] = /\/(.*)\/(.*)/.exec(list[0].url);

				let codeList = [];
				list.forEach((element) => {
					let [url, objName, funName] = /\/(.*)\/(.*)/.exec(element.url);
					if (url.indexOf('?') > -1) {
						url = url.substring(0, url.indexOf('?'));
						funName = funName.substring(0, funName.indexOf('?'));
					}
					funName = `${objName}_${funName}`;
					let res = code(funName, element.name, element.method, url);
					// console.log(res);
					if (res) codeList.push(res);
				});

				var apiCode = generateObjItem(key, name, codeList.join(''));
				return apiCode;
			}
			function code(funName, desc, method, url) {
				return `
          /**
          * ${desc}
          * @param {*} params
          * @returns
          */
			     ${funName}(params) {
			       return service
			           .${method.toLocaleLowerCase()}('${url}', params)
			     },
        `;
			}
		</script>
	</body>
</html>
